package com.qf.java2201.edu.userservice.token.impl;

import com.alibaba.fastjson.JSON;
import com.qf.java2201.edu.userservice.dto.Token;
import com.qf.java2201.edu.userservice.token.TokenService;
import com.qf.java2201.edu.userservice.web.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @date 2022/6/5
 * @desc
 */
@Primary
@Service("tokenService")
@Slf4j
public class TokenServiceImpl implements TokenService {

    /**
     * token过期秒数
     */
    @Value("${token.expire.seconds}")
    private Integer expireSeconds;

    private static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";

    private static Key KEY = null;

    /**
     * 私钥
     */
    @Value("${token.jwtSecret}")
    private String jwtSecret;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Token saveToken(LoginUser loginUser) {
        // 设置  tokenKey
        loginUser.setTokenKey(UUID.randomUUID().toString());

        cacheLoginUser(loginUser);//将用户信息存入redis

        //使用jwt生成token
        String jwtToken = createJWTToken(loginUser);


        return new Token(jwtToken, loginUser.getLoginTime());
    }

    /**
     * 生成jwt
     *
     * @param loginUser
     * @return
     */
    private String createJWTToken(LoginUser loginUser) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(LOGIN_USER_KEY, loginUser.getTokenKey());// 放入一个随机字符串，通过该串可找到登陆用户

        String jwtToken = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, getKeyInstance())
                .compact();

        return jwtToken;
    }


    private Key getKeyInstance() {
        if (KEY == null) {
            synchronized (TokenServiceImpl.class) {
                if (KEY == null) {// 双重锁
                    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(jwtSecret);
                    KEY = new SecretKeySpec(apiKeySecretBytes, SignatureAlgorithm.HS256.getJcaName());
                }
            }
        }

        return KEY;
    }


    //把认证之后的数据存入redis
    private void cacheLoginUser(LoginUser loginUser) {

        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireSeconds * 1000);
        // 根据uuid将loginUser缓存
        //redisTemplate.boundValueOps(getTokenKey(securityUser.getToken())).set(securityUser, expireSeconds, TimeUnit.SECONDS);

        stringRedisTemplate.opsForValue().set(getTokenKey(loginUser.getTokenKey()), JSON.toJSONString(loginUser),expireSeconds, TimeUnit.SECONDS);
    }

    private String getTokenKey(String uuid) {
        return "tokens:" + uuid;
    }



    @Override
    public void refresh(LoginUser loginUser) {
        cacheLoginUser(loginUser);
    }



    //解析token  获取 redis 中的 key  ,根据 key 获取用户信息
    @Override
    public LoginUser getLoginUser(String jwtToken) {
        //从jwt中获取用户的基本信息
        String uuid = getUUIDFromJWT(jwtToken);
        if (uuid != null) {
            //redis:缓存服务器，暂时存放数据，效率比数据库高的键值对数据库。
            //从redis中获取完整的用户数据
            String s = stringRedisTemplate.boundValueOps(getTokenKey(uuid)).get();
            LoginUser loginUser = JSON.parseObject(s, LoginUser.class);
            return loginUser;
        }

        return null;
    }
    //解析token
    private String getUUIDFromJWT(String jwtToken) {
        if ("null".equals(jwtToken) || StringUtils.isBlank(jwtToken)) {
            return null;
        }

        try {
            Claims body = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken).getBody();
            return body.get(LOGIN_USER_KEY,String.class);

        } catch (ExpiredJwtException e) {
            log.error("{}已过期", jwtToken);
        } catch (Exception e) {
            log.error("{}", e);
        }

        return null;
    }
    @Override
    public boolean deleteToken(String jwtToken) {
        String uuid = getUUIDFromJWT(jwtToken);
        if (uuid != null) {
            String key = getTokenKey(uuid);
            String loginUser = stringRedisTemplate.opsForValue().get(key);
            if (loginUser != null) {
                stringRedisTemplate.delete(key);
                return true;
            }
        }
        return false;
    }
}
